/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.toolkit.crypto.util

import cool.taomu.toolkit.crypto.Base64
import java.io.File
import java.nio.charset.Charset
import java.security.KeyPairGenerator
import java.security.Security
import java.util.Date
import org.apache.commons.io.FileUtils
import org.bouncycastle.bcpg.HashAlgorithmTags
import org.bouncycastle.jce.provider.BouncyCastleProvider
import org.bouncycastle.openpgp.PGPEncryptedData
import org.bouncycastle.openpgp.PGPKeyPair
import org.bouncycastle.openpgp.PGPPublicKey
import org.bouncycastle.openpgp.PGPSecretKey
import org.bouncycastle.openpgp.PGPSignature
import org.bouncycastle.openpgp.operator.jcajce.JcaPGPContentSignerBuilder
import org.bouncycastle.openpgp.operator.jcajce.JcaPGPDigestCalculatorProviderBuilder
import org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyPair
import org.bouncycastle.openpgp.operator.jcajce.JcePBESecretKeyEncryptorBuilder

class PgpKeyTool {

	private def static PGPKeyPair genKeyPair(int rsaWidth) {
		var kpg = KeyPairGenerator.getInstance("RSA", "BC");
		kpg.initialize(rsaWidth);
		var kp = kpg.generateKeyPair();
		return new JcaPGPKeyPair(PGPPublicKey.RSA_GENERAL, kp, new Date());
	}

	def static PGPSecretKey getSecretKey(String identity, String passPhrase, int rsaWidth) {
		var keyPair = genKeyPair(rsaWidth);
		var sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build.get(HashAlgorithmTags.SHA1);
		return new PGPSecretKey(
			PGPSignature.DEFAULT_CERTIFICATION,
			keyPair,
			identity,
			sha1Calc,
			null,
			null,
			new JcaPGPContentSignerBuilder(keyPair.getPublicKey().getAlgorithm(), HashAlgorithmTags.SHA1),
			new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.CAST5, sha1Calc).setProvider("BC").build(
				passPhrase.toCharArray)
		)
	}

	def static getPrivateKey(PGPSecretKey key) {
		return new String(new Base64(key.encoded).encode(), Charset.forName("UTF-8"));
	}

	def static getPublicKey(PGPSecretKey key) {
		var pkey = key.publicKey;
		return new String(new Base64(pkey.encoded).encode(), Charset.forName("UTF-8"));
	}

	def static void main(String[] args) {
		Security.addProvider(new BouncyCastleProvider());
		var skey = PgpKeyTool.getSecretKey("aaa", "123456789", 2048);
		FileUtils.writeStringToFile(new File("src/test/resources/privateKey1.txt"), PgpKeyTool.getPrivateKey(skey),
			Charset.forName("UTF-8"));
		FileUtils.writeStringToFile(new File("src/test/resources/publicKey1.txt"), PgpKeyTool.getPublicKey(skey),
			Charset.forName("UTF-8"));
	}
}
